const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const pkgName = require("../package.json").name;

const cssOptions = {
  sourceMap: true,
  importLoaders: 1,
  modules: {
    auto: true,
    mode: "local",
    localIdentName: "[path]-[name]__[local]__[hash:8]",
  },
};

const devServer = {
  host: "127.0.0.1",
  port: 1314,
  hot: true,
  historyApiFallback: true,
  compress: true,
  open: true,
  // headers: {
  //   "Access-Control-Allow-Origin": "*",
  //   "Access-Control-Allow-Credentials": true,
  //   "Access-Control-Allow-Headers": "X-Requested-With,Content-Type",
  //   "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
  //   "Content-Type": "application/json; charset=utf-8",
  // },
};

module.exports = {
  entry: path.resolve(__dirname, "../src/index.tsx"),
  output: {
    path: undefined,
    filename: "static/js/[name].js",
    chunkFilename: "static/js/[name].chunk.js",
    clean: true,
    // publicPath: "/",
    // library: `${pkgName}-[name]`,
    // libraryTarget: "umd",
    // globalObject: "window",
    // chunkLoadingGlobal: `webpackJsonp_${pkgName}`,
  },
  module: {
    rules: [
      {
        test: /\.[jt]sx?$/,
        exclude: /node_modules/,
        use: { loader: "ts-loader", options: { transpileOnly: true } },
      },
      {
        test: /\.module\.css$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: cssOptions,
          },
        ],
      },
      {
        test: /\.module\.s[ac]ss$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: cssOptions,
          },
          "sass-loader",
        ],
      },
      {
        test: /\.s[ac]ss$/,
        exclude: /\.module\.scss$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    new ReactRefreshWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css",
    }),
  ],
  resolve: { extensions: [".ts", ".js", ".tsx", ".jsx"] },
  devServer,
  mode: "development",
  devtool: "inline-source-map",
};
